package cn.hls.dao.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import cn.hls.dao.ACLDao;
import cn.hls.dao.ModuleDao;
import cn.hls.entity.Module;
import cn.hls.entity.vo.ExtTree;
import cn.hls.entity.vo.PageInfo;
import cn.hls.exception.BussinessException;
import cn.hlsconstant.DataAssessEnum;

/**
 * @fileName: ModuelDaoImpl.java
 * @Description: 功能模块接口实现类
 * @author: yinghui.zhang
 * @email: uuhui@163.com
 * @date 2015年4月15日
 * @version V1.0
 */
@Component("moduleDaoImpl")
public class ModuleDaoImpl extends BaseDaoImpl<Module> implements ModuleDao {
	@Resource(name="aclDaoImpl")
	private ACLDao aclDao;
	@SuppressWarnings("unchecked")
	@Override
	public List<ExtTree> loadChildModules(Module module, Long nodeId) throws Exception {
		StringBuilder sb = new StringBuilder();
		List<Object> paramList = new ArrayList<Object>();
		sb.append("select new cn.hls.entity.vo.ExtTree(f.name ,f.id,f.code,(select case when count(id) = 0 then true else false end from Module  where deleted=false and parent.id=f.id) as leaf) from Module f where deleted=?  ");
		paramList.add(false);
		if (nodeId != null) {
			if (nodeId .longValue()==0){
				sb.append(" and parent.id is null");
			}else{
				sb.append(" and parent.id=?");
				paramList.add(nodeId);
			}
		}else{
			sb.append(" and parent.id is null");
		}
		if ((module != null) && (StringUtils.hasText(module.getName()))) {
			sb.append(" and name like ?");
			paramList.add("%" + module.getName() + "%");
		}
		sb.append(" order by sort");
		//return getHibernateTemplate().find(sb.toString(), paramList.toArray());
		return    (List<ExtTree>) find(sb.toString().toString(),paramList.toArray());
	}

	@Override
	public PageInfo<Module> loadModules(Module module, PageInfo<Module> page) throws Exception {
		// 定义查询Hql语句
		StringBuilder selectHql = new StringBuilder();
		// 定义汇总Hql语句
		StringBuilder counthql = new StringBuilder();
		// 定义查询参数
		List<Object> paramList = new ArrayList<Object>();
		selectHql.append("from Module where  deleted=? ");
		paramList.add(false);
		if (module != null) {
			Long fatherId = module.getId();
			if (fatherId == null || fatherId == 0)
				selectHql.append(" and  parent.id is null ");
			else {
				selectHql.append(" and  parent.id=?");
				paramList.add(fatherId);
			}
			if (StringUtils.hasText(module.getName())) {
				selectHql.append(" and name like ?");
				paramList.add("%" + module.getName().trim() + "%");
			}
		}
		counthql.append(" select count(id) ").append(selectHql);
		selectHql.append(" order by sort");

		return find(selectHql.toString(), counthql.toString(), paramList.toArray(), page);
	}

	@Override
	public String deleteModule(Long id) throws Exception {
		try {
			Module module = (Module) find(id);
			if (checkChildren(id)) {
				return "模块[" + module.getName() + "] 存在有子模块,不允许删除！";
			}else{

			aclDao.deleteAclByModule(id);
			delete(id);
			return "ok";
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new BussinessException(DataAssessEnum.DELETE_ERROR,"删除模块数据失败");
		}
	}

	/**
	 * 根据编号查询模块是否存在子模块信息
	 * 
	 * @param id编号
	 * @return boolean
	 */
	private boolean checkChildren(Long id) throws Exception {
		String hql = "select count(id) from Module where parent.id=? and deleted=? ";
		return ((Long) getSession().createQuery(hql).setParameter(0, id).setParameter(1, false).uniqueResult()).longValue() > 0L;
	}

	@Override
	public void updateModuleSort(String ids) throws Exception {
		String[] tempIds = ids.split(",");
		for (int i = 0; i < tempIds.length; i++) {
			String hql = "update Module set sort=? where id=?";
			executeHQLUpdate(hql, new Object[] { i + 1, Long.valueOf(tempIds[i]) });
		}

	}

	public Module findModule(Module entity) throws Exception {
		// 定义查询参数
		List<Object> paramList = new ArrayList<Object>();
		// 定义查询hql语句
		StringBuilder selectHql = new StringBuilder("select m from Module m where  deleted=? and m.parent.id=? ");
		paramList.add(false);
		paramList.add(entity.getParent().getId());
		// 设置name及code查询参数
		if (entity != null) {
			if (StringUtils.hasText(entity.getName())) {
				selectHql.append(" and name=?");
				paramList.add(entity.getName().trim());
			}
			if (StringUtils.hasText(entity.getCode())) {
				selectHql.append(" and code=?");
				paramList.add(entity.getCode().trim());
			}
		}
		Module module;
		try {
			Query query = getSession().createQuery(selectHql.toString());
			for (int i = 0; i < paramList.size(); i++) {
				query.setParameter(i, paramList.get(i));
			}
			module = (Module) query.uniqueResult();
			return module;
		} catch (Exception e) {
			e.printStackTrace();
			throw new BussinessException(DataAssessEnum.SELECT_ERROR,"查询的模块数据不存在");
		}
	}

	@Override
	public Module findModule(String url) throws Exception {
		try {
			if ((url == null) || ("".equals(url))) {
				return null;
			}
			String hql = "select m from Module m where m.url = ? and  deleted=? ";
			Query query = getSession().createQuery(hql);
			query.setParameter(0, url);
			query.setParameter(1, false);
			Module module = (Module) query.uniqueResult();
			return module;
		} catch (Exception e) {
			e.printStackTrace();
			throw new BussinessException(DataAssessEnum.SELECT_ERROR,"链接地址为"+url+"数据不存在");
		}
	}

	@Override
	public Module findModule(String name, String code) throws Exception {
		String hql = "select m from Module m where m.name = ? or m.code=? and  deleted=? ";
		Query query = getSession().createQuery(hql);
		query.setParameter(0, name);
		query.setParameter(1, code);
		query.setParameter(2, false);
		Module module = (Module) query.uniqueResult();
		return module;
	}

}
